package com.ffmpeg.util.infra.handle.file;

import java.io.*;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * @author :wm
 * @description :文件下载
 */
@Component
public class DownloadHandle {

    private final static Logger logger = LoggerFactory.getLogger(DownloadHandle.class);

    public Boolean fileDownLoad(HttpServletResponse response, String filePath) {
        Assert.isTrue(StringUtils.isNotEmpty(filePath), "error.filePath.empty");
        File file = new File(filePath);
        Assert.isTrue(file.exists(), "error.file.not_exist");
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + filePath);

        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            byte[] buff = new byte[1024];
            OutputStream os = response.getOutputStream();
            int i;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            logger.error("{}", e.getMessage());
            return false;
        }
        return true;
    }
}
